package com.cndw.kungfu.ext;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class CommUtil {

	// 将127.0.0.1形式的IP地址转换成十进制整数，这里没有进行任何错误处理
	public static long ipToLong(String strIp) {
		if (strIp == null || strIp.length() == 0) {
			return 0;
		}
		long[] ip = new long[4];
		// 先找到IP地址字符串中.的位置
		int position1 = strIp.indexOf(".");
		int position2 = strIp.indexOf(".", position1 + 1);
		int position3 = strIp.indexOf(".", position2 + 1);
		// 将每个.之间的字符串转换成整型
		ip[0] = Long.parseLong(strIp.substring(0, position1));
		ip[1] = Long.parseLong(strIp.substring(position1 + 1, position2));
		ip[2] = Long.parseLong(strIp.substring(position2 + 1, position3));
		ip[3] = Long.parseLong(strIp.substring(position3 + 1));
		return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
	}

	// 将十进制整数形式转换成127.0.0.1形式的ip地址
	public static String longToIP(long longIp) {
		StringBuffer sb = new StringBuffer("");
		// 直接右移24位
		sb.append(String.valueOf((longIp >>> 24)));
		sb.append(".");
		// 将高8位置0，然后右移16位
		sb.append(String.valueOf((longIp & 0x00FFFFFF) >>> 16));
		sb.append(".");
		// 将高16位置0，然后右移8位
		sb.append(String.valueOf((longIp & 0x0000FFFF) >>> 8));
		sb.append(".");
		// 将高24位置0
		sb.append(String.valueOf((longIp & 0x000000FF)));
		return sb.toString();
	}

	@Deprecated
	public static int ipToInt(String ipAddress) {
		int address = 0;
		if (ipAddress == null || ipAddress.length() == 0) {
			return address;
		}
		String[] addr = ipAddress.split("\\.");
		if (addr.length == 4) {
			address = Integer.parseInt(addr[3]) & 0xFF;
			address |= ((Integer.parseInt(addr[2]) << 8) & 0xFF00);
			address |= ((Integer.parseInt(addr[1]) << 16) & 0xFF0000);
			address |= ((Integer.parseInt(addr[0]) << 24) & 0xFF000000);
		}
		return address;
	}

	/**
	 * Get host IP address
	 * 
	 * @return IP Address
	 */
	public static InetAddress getAddress() {
		try {
			InetAddress inetAddress = null;
			for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
				NetworkInterface networkInterface = interfaces.nextElement();
				if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
					continue;
				}
				Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					inetAddress = (InetAddress) addresses.nextElement();
					if (inetAddress instanceof Inet4Address) {
						if (inetAddress.getHostAddress().startsWith("10")) {//腾讯服暂定如此
							return inetAddress;
						}						
					}					
				}
			}
			return inetAddress;
		} catch (SocketException e) {

		}
		return null;
	}

}
